function info(msg, error=false) {
    var divInfo = $("#info");
    if (error) {
        divInfo.removeClass("alert-info");
        divInfo.addClass("alert-danger");
    } else {
        divInfo.removeClass("alert-danger");
        divInfo.addClass("alert-info");
    }
    divInfo.text(msg);
    divInfo.css("visibility", "visible");
}

function appendResult(src, result) {
    if (result.status != 0) {
        return;
    }
    let table = $("<table/>");
    const colNum = result.head.length;
    let row = $(table[0].insertRow(-1));
    for (let i = 0; i < colNum; i++) {
        row.append("<th>" + result.head[i] + "<th/>");
    }
    for (let i in result.data) {
        row = $(table[0].insertRow(-1));
        for (let j = 0; j < result.data[i].length; j++) {
            row.append("<td>" + result.data[i][j] + "<td/>");
        }
    }
    table.addClass("dx-table");
    table.mark(src);
    $("#result").append("<h2>" + result.table + "</h2>");
    $("#result").append(table);
}

function query(content) {
    console.log("Searching " + content);
    if (content.length === 0) {
        info("搜索内容不能为空!", true);
        return false;
    }
    info("正在搜索 \"" + content + "\"的相关信息...")
    doProgress(0);
    const beginTime = new Date().getTime();
    const total = 13;
    let finished = 0;
    $("#bar").addClass("active");
    $("#query").prop('disabled', true);
    $("#submit").prop('disabled', true);
    $("#result").empty();
    for (let i = 0; i < total; i++) {
        $.get("/s/" + content + "/" + i, function(result, status) {
            finished += 1;
            doProgress((finished/total) * 100);
            appendResult(content, result);
            if (finished == total) {
                var delta = new Date().getTime() - beginTime;
                info("查询完毕! 耗时 " + delta + " 毫秒");
                $("#bar").removeClass("active");
                $("#query").prop('disabled', false);
                $("#submit").prop('disabled', false);
            }
        });
    }
}
function doProgress(value, relative=false) {
    let bar = $("#bar");
    let newVar = parseInt(value);
    if (relative) {
        const current = parseInt(bar.attr("aria-valuenow"));
        newVar += current;
    }
    bar.text(newVar + "%");
    bar.attr("aria-valuenow", newVar);
    bar.css("width", newVar + "%");
    bar.css("visibility", "visible");
}

$(document).ready(function(){
    $("#submit").click(function(){
        query( $("#query").val() );
    });

    $('#query').keypress(function (e) {
        if (e.which == 13) {
            query( $("#query").val() );
            return false;
        }
    });
});
